#ifndef BUFFER_H
#define BUFFER_H
#include <string>
#include <string.h>
#include <vector>
#include <assert.h>
#include <unistd.h>  
#include <sys/uio.h>
class CBuffer
{
public: 
    explicit CBuffer(size_t initialSize = 1024);
    ~CBuffer()= default;

    size_t readableBytes() const;
    size_t writeableBytes() const;
    size_t prependableBytes() const;
    
    const char* peek() const;
    char* beginWrite();
    const char* beginWrite() const;
    void ensureWriteableBytes(size_t len);
    void  hasWritten(size_t len);
    void  unwrite(size_t len);

    void retrieve(size_t len);
    void retrieveUntil(const char* end);
    void retrieveAll();
    std::string retrieveAllAsString();
    std::string retrieveAllAsString(size_t len);

    void append(const std::string &str);
    void append(const char* str, size_t len);
    void append(const void* data, size_t len);
    ssize_t readFd(int fd, int* Errno);
private:
    char *begin()
    {
        return &*m_buffer.begin(); 
    }
    //常量默认调用此重载函数
    const char* begin() const
    {
        return &*m_buffer.begin();
    }
    void makeSpace(size_t len)
    {
        //剩余空间不足等于len, 则移动可读数据只最前面，腾出空间
        if(writeableBytes() + prependableBytes() < len)
        {
            m_buffer.resize(m_writerIndex + len + 1);
        }
        else  //剩余空间大于等于len，则可移动数据只最前面，腾出空间 
        {
            size_t readable = readableBytes();
            std::copy(begin() + m_readerIndex, begin() +m_writerIndex, begin());
            m_readerIndex = 0;
            m_writerIndex = m_readerIndex + readable;
            assert(readable == readableBytes());

        }
    }
private:
    std::vector<char> m_buffer;
    size_t m_readerIndex;
    size_t m_writerIndex;
};
#endif
